<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5_LocalStorage</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <div class="wrapper">
        <h2>LOCAL TAPAS</h2>
        <p></p>
        <ul class="plates">
            <li>Loading Tapas...</li>
        </ul>
        <form class="add-items">
            <input type="text" name="item" autofocus placeholder="Item Name" required>
            <input type="submit" value="+ Add Item">
        </form>
    </div>
    <script>
        // 1. todolist  form + ul
        // 2. Loading 
        // 3. 前端数据持久化 前端有数据库 约5m缓存
        // 为什么每次事先把要选的元素赋值给一个常量?
        // 性能--不用每次去查dom树,每次只用去找个地址
        // 声明写在前面,不容易由暂时性死区,可读性也高
        const addItems = document.querySelector('.add-items');
        const itemsList = document.querySelector('.plates');
        const items = JSON.parse(localStorage.getItem("items")) || [];//有本地存储的话,用本地存储.没有就空数组

        function populateList(plates = [], platesList) {
            // 将 todolist 显示到列表
            platesList.innerHTML = plates.map((plate, i) => `
                <li>
                    <input type="checkbox" data-index=${i} id="item${i}"
                    ${plate.done ? 'checked' : ''}/>
                    <label for ="item${i}">${plate.text}</label>
                </li>
            `)
        };

        function addItem(event) {
            event.preventDefault();
            const text = this.querySelector('[name=item]').value.trim();
            console.log(text);
            const item = {
                text,//es6 对象的省略写法
                done: false
            }
            items.push(item);
            populateList(items, itemsList);// 渲染ul
            // console.log(JSON.stringify(items));// 变成字符串文本
            // JSON.parse(); // 变成数组
            localStorage.setItem('items', JSON.stringify(items));// 本地存储
            this.reset();
        };

        // function init() {
        //     // 取出 loaclstorage
        //     // [] .length > 0
        //     // populateList
        //     // const storageItems = 
        //     if (storageItems.length) {
        //         // items = [...storageItems] 常量不支持整体修改
        //         populateList(storageItems, itemsList)
        //     };
        addItems.addEventListener('submit', addItem);
        populateList(items, itemsList);
    </script>
</body>

</html>